package com.general.framework.wukong.blockingQueue.interview;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class ArrayBlockingQueueDemoByAtomicInteger {
    public static void main(String[] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        AtomicInteger remainingTasks = new AtomicInteger(10);
        Interviewer interviewer = new Interviewer(queue, remainingTasks);
        Interviewee interviewee = new Interviewee(queue, remainingTasks);
        new Thread(interviewer).start();
        new Thread(interviewee).start();
    }
}

class Interviewer implements Runnable {
    private final BlockingQueue<String> queue;
    private final AtomicInteger remainingTasks;

    public Interviewer(BlockingQueue<String> queue, AtomicInteger remainingTasks) {
        this.queue = queue;
        this.remainingTasks = remainingTasks;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            String candidate = "Candidate" + i;
            try {
                queue.put(candidate);
                System.out.println("已安排好了第 " + candidate + " 位候选者");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            remainingTasks.decrementAndGet();
        }
    }
}

class Interviewee implements Runnable {
    private final BlockingQueue<String> queue;
    private final AtomicInteger remainingTasks;

    public Interviewee(BlockingQueue<String> queue, AtomicInteger remainingTasks) {
        this.queue = queue;
        this.remainingTasks = remainingTasks;
    }

    @Override
    public void run() {
        while (remainingTasks.get() > 0) {
            System.out.println(remainingTasks.get());
            try {
                Thread.sleep(1000);
                String candidate = queue.take();
                System.out.println("第 " + candidate + " 位候选者面试完毕");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}